package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SPUMapper;
import cn.tedu.csmall.product.pojo.entity.*;
import cn.tedu.csmall.product.pojo.param.BrandAddNewParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.service.BrandService;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.product.web.ServiceCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class BrandServiceImpl implements BrandService {

    @Autowired
    BrandMapper brandMapper;
    @Autowired
    BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SPUMapper spuMapper;

    @Override
    public void addNew(BrandAddNewParam brandAddNewParam) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",brandAddNewParam.getName());
        int count = brandMapper.selectCount(queryWrapper);
        if (count > 0) {
            String message = "【ServiceException:添加品牌失败，品牌名称已经被占用！】";
            log.debug("【log.info:添加品牌失败，品牌名称已经被占用！】");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewParam, brand);
        brand.setSales(0);
        brand.setProductCount(0);
        brand.setCommentCount(0);
        brand.setPositiveCommentCount(0);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        int rows = brandMapper.insert(brand);
        if (rows != 1) {
            String msg = "添加品牌失败，服务器忙，请稍后再试！";
            log.warn(msg);
            // 抛出异常就能回滚
            throw new ServiceException(ServiceCode.ERR_INSERT, msg);
        }
    }

    @Override
    public void deleteById(Long brandId) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",brandId);
        int countByName = brandMapper.selectCount(queryWrapper);
        if (countByName > 0) {

            // 检查是否有类别关联到了此品牌，如果有，则不能删除该品牌
            QueryWrapper<BrandCategory> pictureQueryWrapper = new QueryWrapper<>();
            pictureQueryWrapper.eq("brand_id",brandId);
            int countByBrandId1 = brandCategoryMapper.selectCount(pictureQueryWrapper);
            if (countByBrandId1 > 0) {
                throw new ServiceException(ServiceCode.ERR_CONFLICT, "该品牌有附属类别，请转移后删除！");
            }

            // 检查是否有SPU关联到了此品牌，如果有，则不能删除该相册
            QueryWrapper<SPU> spuQueryWrapper = new QueryWrapper<>();
            spuQueryWrapper.eq("brand_id",brandId);
            int countByBrandId2 = spuMapper.selectCount(spuQueryWrapper);
            if (countByBrandId2 > 0) {
                throw new ServiceException(ServiceCode.ERR_CONFLICT, "该品牌有附属SPU，请转移后删除！");
            }

            // 不会抛出异常（即该品牌没有附属的东西），则允许删除
            int rows = brandMapper.deleteById(brandId);
            if (rows != 1) {
                String msg = "删除品牌失败，服务器忙，请稍后再试！";
                log.warn(msg);
                // 抛出异常就能回滚
                throw new ServiceException(ServiceCode.ERR_DELETE, msg);
            }
            return;
        }
        String message = "【ServiceException:删除失败，没有该品牌ID！】";
        log.debug("【log.info:删除失败，没有该品牌ID！！】");
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
    }

    @Override
    public void updateInfoById(Long id, BrandUpdateInfoParam brandUpdateInfoParam) {

        // 修改前判断数据是否存在
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById = brandMapper.selectCount(queryWrapper);
        if (countById == 0) {
            String message = "修改品牌失败，没有该品牌！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 修改前判断品牌名称是否被其他品牌占用，如果占用则抛出异常
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name",brandUpdateInfoParam.getName())
                .ne("id",id);
        int countByName = brandMapper.selectCount(queryWrapper1);
        if (countByName > 0) {
            String message = "修改品牌失败，名称被占用！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行修改
        log.debug("开始处理【修改品牌详情】的业务，参数：{}",brandUpdateInfoParam);
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateInfoParam,brand);
        brand.setId(id);
        int rows = brandMapper.updateById(brand);
        if (rows != 1) {
            String msg = "更新品牌详情失败，服务器忙，请稍后再试！";
            log.warn(msg);
            // 抛出异常就能回滚
            throw new ServiceException(ServiceCode.ERR_UPDATE, msg);
        }
        log.debug("新的品牌数据更新到数据库完成！");
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum) {
        int pageSize = 5;
        return list(pageNum, pageSize);

    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【分页查询品牌列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<BrandListItemVO> list = brandMapper.list();
        PageInfo<BrandListItemVO> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverter.convert(pageInfo);
    }

    @Override
    public List<BrandListItemVO> listEnable() {
        log.debug("开始处理【查询所有启用的品牌列表】的业务");
        List<BrandListItemVO> list = brandMapper.listEnable();
        return list;
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {

        log.debug("开始处理【根据ID查询品牌】的业务，ID值为：{}", id);
        BrandStandardVO result = brandMapper.getStandardById(id);
        if (result == null) {
            String message = "【根据ID查询品牌】失败，品牌数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return result;
    }

    @Override
    public void setEnable(Long id, Integer enable) {

        // 修改前判断数据是否存在
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById = brandMapper.selectCount(queryWrapper);
        if (countById == 0) {
            String message = "修改启用或者禁用失败，没有该品牌！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Brand brand = new Brand()
                .setId(id)
                .setEnable(enable)
                .setGmtModified(LocalDateTime.now());
        int rows = brandMapper.updateById(brand);
        if (rows != 1) {
            String msg = "设置启用或者禁用失败，服务器忙，请稍后再试！";
            log.warn(msg);
            // 抛出异常就能回滚
            throw new ServiceException(ServiceCode.ERR_UPDATE, msg);
        }
        log.debug("设置品牌的启用或者禁用到数据库完成！");
    }
}
